package com.aspire.nm.component.cmppserver.filter;


import javax.annotation.Resource;

import org.apache.mina.core.filterchain.IoFilterAdapter;
import org.apache.mina.core.session.IoSession;
import org.apache.mina.core.write.WriteRequest;
import org.springframework.stereotype.Service;

import com.aspire.nm.component.cmppserver.filter.coder.packet.CmppConnectPacket;
import com.aspire.nm.component.cmppserver.filter.coder.packet.CmppConnectRespPacket;
import com.aspire.nm.component.cmppserver.filter.coder.packet.CmppTerminateRespPacket;
import com.aspire.nm.component.cmppserver.runTime.SysRunTimeService;
import com.aspire.nm.component.cmppserver.util.LogService;


@Service
public class LoginFilter extends IoFilterAdapter {

    @Resource
    private LogService logService;
    @Resource
    private SysRunTimeService sysRunTimeService;

    public void messageSent(NextFilter nextFilter, IoSession session, WriteRequest writeRequest) throws Exception {
        if (writeRequest.getMessage() instanceof CmppConnectRespPacket) {
            CmppConnectRespPacket cmppConnectRespPacket = (CmppConnectRespPacket) writeRequest.getMessage();

            CmppConnectPacket cmppConnectPacket = (CmppConnectPacket) cmppConnectRespPacket.bizParams;
            if (cmppConnectRespPacket.getStatus() == CmppConnectRespPacket.STATUS_SUCCESS) {
                sysRunTimeService.addSession(cmppConnectPacket.getSourceAddr(), session,cmppConnectRespPacket.getVersion());
                
                logService.connect(session, cmppConnectPacket);
                logService.connectResp(session, cmppConnectRespPacket);
            } else {
                session.close(true);
                
                logService.connect(session, cmppConnectPacket);
                logService.connectResp(session, cmppConnectRespPacket);
                
                return;
            }
            
        } else if (writeRequest.getMessage() instanceof CmppTerminateRespPacket) {
            session.close(true);
            return;
        }
        nextFilter.messageSent(session, writeRequest);
    }

    public void sessionClosed(NextFilter nextFilter, IoSession session) throws Exception {

        logService.close(session);
        sysRunTimeService.removeSession(session);
        nextFilter.sessionClosed(session);
    }
    
}
